import {getToken} from "@utils/storage.js";
import useUserStore from "@/store/modules/user.js";
import store from "@/store/index.js";

const user = useUserStore(store)
/**
 * 单点登录
 */
const init = async () => {
    let path = window.location.pathname
    let whiteRoute = ['/user/cas-fail', '/scanCode/scanCodeModal']
    let casFailPath = '/user/cas-fail'
    if (import.meta.env.VITE_SSO == 'true' && !whiteRoute.includes(path)) {
        console.log("-------单点登录开始-------");
        let token = getToken();
        let st = getUrlParam("ticket");
        let sevice = window.location.protocol + "//" + window.location.host
        if (token) {
            loginSuccess();
        } else {
            if (st) {
                await validateSt(st, sevice, casFailPath);
            } else {
                console.log("-------单点登录失败，没有ticket参数-------")
                let serviceUrl = encodeURIComponent(sevice);
                window.location.href = import.meta.env.VITE_CAS_BASE_URL + '/login?service=' + sevice + window.location.pathname + window.location.search;
                throw "-------单点登录失败，没有ticket参数-------"
            }
        }
        console.log("-------单点登录结束-------");
    }else{
    }
};
const SSO = {
    init: init
};

function getUrlParam(paraName) {
    let url = document.location.toString();
    let arrObj = url.split("?");
    // ?id=xxx&platform=xxx&ticket=xxx
    if (arrObj.length > 1) {
        let arrPara = arrObj[1].split("&");
        let arr;
        for (let i = 0; i < arrPara.length; i++) {
            arr = arrPara[i].split("=");

            if (arr != null && arr[0] == paraName) {
                return arr[1];
            }
        }
        return "";
    }
    else {
        return "";
    }
}

async function validateSt(ticket,service,casFailPath,callback){
    let params = {
        ticket: ticket,
        service:service
    };


    await user.ValidateLogin(params).then(res => {
        console.log("ValidateLogin", res)
        // let sevice = window.location.protocol + "//" + window.location.host
        if(res.success){
            loginSuccess();
        }else{
            window.location.href = import.meta.env.VITE_CAS_BASE_URL + '/login'
            throw '单点报错'
        }
    }).catch((err) => {
        console.log('err', err)
        let sevice = window.location.protocol + "//" + window.location.host
        let search = window.location.search
        if(search.includes('?ticket')){
            search = search.split('?ticket')[0]
        }else if (search.includes('&ticket')){
            search = search.split('&ticket')[0]
        }
        window.location.href = import.meta.env.VITE_CAS_BASE_URL + '/login'
        throw '单点报错'
    });
}

function loginSuccess () {
    // router.push(window.location.pathname + window.location.search);
}
export default SSO;
